package cn.gcjxsc.service.merchant.redpack;

import cn.gcjxsc.common.data.query.RedPackRecordQuery;
import cn.gcjxsc.common.data.vo.RedPackRecordVo;
import cn.gcjxsc.entity.merchant.redpack.RedPackRecord;
import cn.gcjxsc.entity.merchant.redpack.RedPackRecord_;
import cn.gcjxsc.repository.merchant.redpack.RedPackRecordRepository;
import cn.gcjxsc.repository.specs.RedPackSpec;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class RedPackRecordService {
    @Autowired
    private RedPackRecordRepository recordRepository;

    public RedPackRecordVo converter(RedPackRecord record) {
        RedPackRecordVo redPackRecordVo = new RedPackRecordVo();
        BeanUtils.copyProperties(record, redPackRecordVo);
        return redPackRecordVo;
    }

    @Transactional
    public List<RedPackRecord> saveOrUpdate(RedPackRecord... records) {
        List<RedPackRecord> redPackRecords = Arrays.asList(records);
        return recordRepository.save(redPackRecords);
    }

    public RedPackRecord findBySnAndType(String sn, Integer type) {
        return recordRepository.findBySourceSnAndType(sn, type);
    }

    public List<RedPackRecord> findByOrderSn(String sn) {
        return recordRepository.findBySourceSn(sn);
    }

    public Page<RedPackRecord> findList(RedPackRecordQuery filter, int page, int pageSize) {
        PageRequest pageRequest = new PageRequest(page - 1, pageSize, new Sort(Sort.Direction.DESC, RedPackRecord_.created.getName()));
        return recordRepository.findAll(RedPackSpec.buildSpec(filter), pageRequest);
    }

}
